﻿// -----------------------------------------------------------------------
// <copyright file="ScreenOneView.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using SS.WPF.Framework.ValidationRule;

namespace TestFramework.Views
{
    /// <summary>
    /// Interaction logic for UserControl1.xaml
    /// </summary>
    public partial class ScreenOneView : UserControl
    {
        public ScreenOneView()
        {
            InitializeComponent();
        }

        private void OnClick(object sender, RoutedEventArgs e)
        {
            var uiElement = FocusManager.GetFocusedElement(this) as UIElement;
            if (uiElement != null)
            {
                uiElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                uiElement.Focus();
            }
        }

        private void UserName_Loaded(object sender, RoutedEventArgs e)
        {
            this.TextLoad(sender);
        }

        private void UserName_TextChanged(object sender, TextChangedEventArgs e)
        {
            this.TextChange(sender);
        }

        private void TextLoad(object sender)
        {
            var textBox = (TextBox)sender;
            var bindingExpression = BindingOperations.GetBindingExpression(textBox, TextBox.TextProperty);

            if (!textBox.IsLoaded)
            {
                return;
            }

            bindingExpression.UpdateSource();
        }

        private void TextChange(object sender)
        {
            var textBox = (TextBox)sender;
            var bindingExpression = BindingOperations.GetBindingExpression(textBox, TextBox.TextProperty);

            if (!textBox.IsLoaded)
            {
                return;
            }

            var binding = BindingOperations.GetBinding(textBox, TextBox.TextProperty);
            if (binding != null && binding.ValidationRules != null)
            {
                foreach (var validationItem in binding.ValidationRules)
                {
                    var pathExistValidationRule = validationItem as IValidationRuleCommon;
                    if (pathExistValidationRule != null)
                    {
                        pathExistValidationRule.IsEnabled = false;
                        bindingExpression.UpdateSource();
                        pathExistValidationRule.IsEnabled = true;
                        bindingExpression.UpdateSource();
                    }
                }
            }
        }
    }
}
